from PySide6.QtWidgets import QDialog,QMessageBox
from PySide6 import QtCore,QtWidgets
from sqlalchemy.orm import Session
from settings.publicvar import engine
from views.login.Login import *
from views.home.homeMain import HomeViews
from views.login.model.User import CreateUser

class LoginView(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_LoginWindow()
        self.ui.setupUi(self)
        self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.shadow = QtWidgets.QGraphicsDropShadowEffect(self)
        self.shadow.setOffset(0, 0)
        self.shadow.setBlurRadius(15)
        self.shadow.setColor(QtCore.Qt.black)
        self.ui.frame.setGraphicsEffect(self.shadow)
        self.ui.tLogin.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.ui.tRigster.clicked.connect(lambda: self.ui.stackedWidget.setCurrentIndex(1))
        self.ui.login.clicked.connect(self.loginFun)
        self.ui.rrigster.clicked.connect(self.rigsterFun)
        # 在编写程序时启用
        self.ui.lusername.setText('hrj')
        self.ui.lpassword.setText('hrj')
        self.session = Session(engine)
        self.home = HomeViews()

    def loginFun(self):
        username = self.ui.lusername.text().strip()
        password = self.ui.lpassword.text().strip()
        user = self.session.query(CreateUser).filter(CreateUser.username == username,CreateUser.password == password).first()
        if username== '' or password=='':
            QMessageBox.critical(None,'登录失败','输入的用户或密码不能为空！')
        elif user is not None:
            self.home.show()
            self.hide()
        else:
            QMessageBox.critical(None, '登录失败', '输入的用户或密码不正确，请重新输入！')

    def rigsterFun(self):
        username = self.ui.rusername.text().strip()
        password = self.ui.rpassword.text().strip()
        passwordSure = self.ui.rpasswordSure.text().strip()
        if username == '' or password == '' or passwordSure=='':
            QMessageBox.critical(None, '注册失败', '输入的用户或密码不能为空！')
        elif passwordSure != password:
            QMessageBox.critical(None, '注册失败', '两次输的密码不一致，请重新输入！')
        else:
            # 写入数据库
            user = self.session.query(CreateUser).filter(CreateUser.username == username).first()
            if user is not None:
                QMessageBox.critical(None, '错误', '用户已经存在，不用注册,跳转到登录页')
            else:
                with Session(engine) as session,session.begin():
                    user = CreateUser(username=username, password=password)
                    session.add(user)
                QMessageBox.critical(None, '注册成功', '恭喜你，注册成功！')
            # 切换到登录页
            self.ui.stackedWidget.setCurrentIndex(0)